import './Login.scss'
import NavBarAgain from "@/components/NavBarAgain.jsx";
import {Button, Form, Toast} from "antd-mobile";
import {Input} from "antd-mobile/2x";
import {queryCode, queryLogin} from "@/api/index.js";
import {useState} from "react";
import {connect} from "react-redux";
import {action} from "@/store/action/index.js";


const validate = {
    phone: {
        validator: (rule, value) => {
            if (!value.trim()) {
                return Promise.reject(new Error('请输入手机号'))
            }
            if (!/^1[3456789]\d{9}$/.test(value)) {
                return Promise.reject(new Error('手机号格式不正确'))
            }
            return Promise.resolve();
        }
    },
    code: {
        validator: (rule, value) => {
            console.log('验证码', value)
            if (!value || !value.trim()) {
                return Promise.reject(new Error('请输入验证码'))
            }
            if (!/^\d{6}$/.test(value)) {
                return Promise.reject(new Error('验证码格式不正确'))
            }
            return Promise.resolve();
        }
    }
}

const Login = function Login(props) {
    const {queryUserInfoAsync,navigate,usp} = props

    const [formIns] = Form.useForm();
    let [sendText, setSendText] = useState('发送验证码');
    let [sendDisable, setSendDisable] = useState(false);
    const submit =async (values) => {
        try{
            await formIns.validateFields(['phone', 'code']);
            const {code:codeHttp,data,msg} = await queryLogin(values)
            if(codeHttp !== '200'){
                Toast.show({
                    icon: "fail",
                    content: msg,
                })
                await formIns.resetFields(['code'])
                return
            }
            localStorage.setItem('token',data.access_token)
            await queryUserInfoAsync()
            // eslint-disable-next-line react/prop-types
            let to = usp.get('to')
            Toast.show({
                icon: "success",
                content: '登录成功',
                duration: 1000,
                onClose: () => {

                }
            })
            to? navigate(to, {replace: true}) :navigate(-1)
        }catch (e) { /* empty */ }
       
    }

    let timer = null,num = 61
    const countDown = () => {
        num--
        if(num>0){
            setSendText(num+'秒后重新发送')
        }else{
            setSendText('发送验证码')
            setSendDisable(false)
            clearInterval(timer)
            timer = null
        }
}
    const sendCode = async () => {
        try {
            console.log('验证手机号')
            await formIns.validateFields(['phone']);
            setSendDisable(true)
           const res = await queryCode(formIns.getFieldValue('phone'))

            if (res.code !== '200') {
                Toast.show({
                    icon: "fail",
                    content: "验证码发送失败",
                })
                setSendDisable(false)
            }
                // setSendText('秒后重新发送')
                Toast.show({
                    icon: "success",
                    content: "验证码发送成功",
                })
            countDown()
            if(!timer){
                timer = setInterval(countDown,1000)
            }
        } catch (e) {
            console.log(e)
        }
    }
    return <div className="login-box">
        <NavBarAgain title="登录/注册"/>
        <Form layout="horizontal" style={{'--border-top': 'none'}}
              footer={<Button color="primary" type="submit" block>提交</Button>}
              onFinish={submit}
              form={formIns}
              initialValues={{phone: '', code: ''}}
        >
            <Form.Item label="手机号" name="phone" rules={[validate.phone]}>
                <Input placeholder="请输入手机号"/>
            </Form.Item>
            <Form.Item label="验证码" name="code" rules={[validate.code]}
                       extra={<Button color="primary" size="small" disabled={sendDisable} onClick={sendCode}>{sendText}</Button>}
            >
                <Input placeholder="请输入验证码"/>
            </Form.Item>
        </Form>
    </div>;
}
export default connect(null,action.base)(Login)